import json
from django.http import HttpResponse
from django.core.cache import cache
from datetime import date, datetime,timedelta
import random
from booking.models import User,BasicDate
from booking.cache.caches import check

def getdict(users):
    ans = []
    for i in users:
        dc = {}
        dc['name'] = i.name
        dc['id'] = i.openid
        dc['checked'] = False
        ans.append(dc)
    return ans

def getuserdata(request):
    data = json.loads(request.body)
    id = data['id']
    if id == 0:
        users = User.objects.filter(power=3)
    elif id == 1:
        users = User.objects.filter(power=1)
    ans = getdict(users)
    return HttpResponse(json.dumps({"datelist": ans}))

def powt(request):
    data = json.loads(request.body)
    li = data['li']
    res = True
    for i in li:
        ids = li['id']
        u = User.objects.filter(openid=ids).first()
        if u.power == 3:
            res = False
        else:
            u.power == 3
        u.save()
    if res:
        return HttpResponse(json.dumps({"ret":'F1'}))
    else:
        return HttpResponse(json.dumps({"ret":'F2'}))

def pows(request):
    data = json.loads(request.body)
    li = data['li']
    res = True
    for i in li:
        ids = li['id']
        u = User.objects.filter(openid=ids).first()
        if u.power == 1:
            res = False
        else:
            u.power == 1
        u.save()
    if res:
        return HttpResponse(json.dumps({"ret":'F1'}))
    else:
        return HttpResponse(json.dumps({"ret":'F2'}))
def dels(request):
    data= json.loads(request.body)
    li = data['li']
    for i in li:
        ids = i['id']
        User.objects.filter(openid=id).delete()
    return HttpResponse(json.dumps({"ret":'F1'}))


def redo(request):
    cache.clear()
    check(datetime.now())
    return HttpResponse(json.dumps({"ret":'F1'}))

def qr(request):
    data = json.loads(request.body)
    das = data['das']
    _ = BasicDate.objects.all().first()
    _.NUMS = das
    _.save()
    return HttpResponse(json.dumps({"ret":'F1'}))

def getunck(request):
    nums = cache.get('ids')
    return HttpResponse(json.dumps({"nums": 0 if not nums else len(nums)}))

